package com.pi.base.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.pi.base.common.BasePage;
import com.pi.base.constant.SysStatics;
import com.pi.base.entity.SysGroup;
import com.pi.base.entity.SysMenu;
import com.pi.base.entity.SysMenuExample;
import com.pi.base.entity.SysParameter;
import com.pi.base.entity.SysRole;
import com.pi.base.entity.SysUser;
import com.pi.base.service.ISysGroupService;
import com.pi.base.service.ISysMenuService;
import com.pi.base.service.ISysParameterService;
import com.pi.base.service.ISysRoleService;
import com.pi.base.service.ISysUserService;
import com.pi.base.util.DateTimeUtil;
import com.pi.base.util.JsonTool;
import com.pi.base.util.SysAuthUtil;

@Controller
@RequestMapping("/view")
public class ViewController extends BaseController{
	
	private final Logger logger = LoggerFactory.getLogger(ViewController.class);
	
	public static final String PAGE_LEVEL_SIGNL = "/";
	@Resource
	private ISysRoleService sysRoleService;
	@Resource
	private ISysUserService sysUserService;
	@Resource
	private ISysMenuService sysMenuService;
	@Resource
	private ISysGroupService sysGroupService;
	@Resource
	private ISysParameterService sysParameterService;
	
	/**
	 * 直接跳转页面，不做任何参数的传值
	 * @param id
	 * @param menuId
	 * @return
	 * 1、role/roleAdd.jsp
	 */
	@RequestMapping(value = "/goViewWithoutData/{id}_{menuId}")
	public String goViewWithoutData(@PathVariable("id") String id,
            @PathVariable("menuId") String menuId){
		logger.info("goPage:"+"system/"+id+PAGE_LEVEL_SIGNL+menuId);
		return "system/"+id+PAGE_LEVEL_SIGNL+menuId;
	}
	 
	//******************主页模块**********************
	 /**
	  * 初始化主页
	  * @param session
	  * @param model
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("/goMain")
	 public String goMain(HttpSession session,ModelMap model) throws Exception {
		 SysUser loginUser = this.getLoginedUserInfo(session);
		 List<SysMenu> systemMenuList = new ArrayList<SysMenu>();
		 
		 if(SysStatics.SysUser_IsSuperAdmin == loginUser.getSuperadmin()){
			// 如果是超级管理员，则获取所有的菜单权限
			 systemMenuList = sysMenuService.getAllMenuListLevel2();

		 }else {
			 int roleId = getLoginedUserRoleInfo(session).getId();
			 systemMenuList = sysUserService.getAllMenuByRoleIdAndLevel(roleId, SysStatics.SysMenu_Level_Two);
			// 查询按钮权限列表。
			 String buttonCodeStrs = sysRoleService.getButtonCodeStrsByRoleId(roleId);
			 //存入session
			 session.setAttribute(SysStatics.WEB_BTNAUTH_SESSION,  "," +buttonCodeStrs+ ",");
		 }
		 if(systemMenuList!=null && systemMenuList.size()>=1){
			 
			 int firstMenuId = systemMenuList.get(0).getId();
			 session.setAttribute(SysStatics.WEB_FIRSTMENU_SESSION, firstMenuId+"");
			 
			 model.addAttribute("systemMenuId", firstMenuId);
		 }
	
		 model.addAttribute("txtUserName", loginUser.getName());
		 model.addAttribute("txtUserId", loginUser.getId());
		 
		 return "system/common/main";
	 }
	 
	 /**
	  * 初始化顶部
	  * @param session
	  * @param model
	  * @return
	  * @throws Exception
	  */
	 @RequestMapping("/getTop")
	 public String getTop(HttpSession httpSession,ModelMap model) throws Exception {
		 List<SysMenu> sysMenuList ;
		 String strRoleName;
		 SysUser loginUser = this.getLoginedUserInfo(httpSession);
		 if(SysStatics.SysUser_IsSuperAdmin == loginUser.getSuperadmin()){ //超级管理员
			 strRoleName = "超级管理员";
			 sysMenuList = sysMenuService.getAllMenuListLevel2(); 
		 }else{
			 SysRole loginRole = this.getLoginedUserRoleInfo(httpSession);
			 strRoleName = loginRole.getName();
			 sysMenuList = sysUserService.getAllMenuByRoleIdAndLevel(loginRole.getId(), SysStatics.SysMenu_Level_Two);
		 }
		 model.addAttribute("loginedUser", loginUser);
		 model.addAttribute("systemMenuList", sysMenuList);
		 model.addAttribute("txtUserName", loginUser.getName());
		 model.addAttribute("txtRoles", strRoleName);
		 return "system/common/top";
	 }
	 
	/**
	 * 初始化左菜单
	 * 
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getLeftmenu")
	public String getLeftmenu(HttpSession httpSession, ModelMap model,@RequestParam(required=false) String systemMenuId)
			throws Exception {
		if (systemMenuId == null) {
			systemMenuId = (String) httpSession.getAttribute(SysStatics.WEB_FIRSTMENU_SESSION);
		}
		List<SysMenu> menuList ;
//		SysUser loginUser = this.getLoginedUserInfo(httpSession);
//		 if(SysStatics.SysUser_IsSuperAdmin == loginUser.getSuperadmin()){ //超级管理员		 
//			 SysMenuExample example = new SysMenuExample();
//			 example.createCriteria().andLevelIn(Arrays.asList(new Integer[] { 3, 4 }));
//			 menuList = sysMenuService.getMenuListByExample(example);
//		 }else{
		
			 menuList = sysUserService.getAllMenuByRoleIdAndLevel(this.getLoginedUserRoleInfo(httpSession).getId(),3,4);
//		 }
		 menuList = SysAuthUtil.turnListToTreeList(menuList, SysMenu.class, "getParentid", systemMenuId,  "getId", "getParentid", "setSubList");
		 model.addAttribute("menuList", menuList);
		return "system/common/left";
	}
	
	/**
	 * 菜单导航
	 * @param httpSession
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getWelcome")
	public String getWelcome(HttpSession httpSession, ModelMap model) throws Exception {
		 SysUser loginUser = this.getLoginedUserInfo(httpSession);
		 List<SysMenu> menuList;
		 if(SysStatics.SysUser_IsSuperAdmin == loginUser.getSuperadmin()){ //超级管理员	
			// 如果是超级管理员，则获取所有的菜单权限。
			 SysMenuExample example = new SysMenuExample();
			 example.createCriteria().andLevelIn(Arrays.asList(new Integer[] { 2, 3, 4 }))
			 .andNameNotLike("工作人员%");
			 menuList = sysMenuService.getMenuListByExample(example);
		 }else {
			 menuList = sysUserService.getAllMenuByRoleIdAndLevel(this.getLoginedUserRoleInfo(httpSession).getId(), 2, 3, 4);
		 }
		 menuList = SysAuthUtil.turnListToTreeList(menuList, SysMenu.class, "getParentid", "1", "getId", "getParentid", "setSubList");
		 model.addAttribute("menuList", menuList);
		 model.addAttribute("loginedUser", loginUser);
		 return "system/common/welcome";
	}
	
	/**
	 * 底部
	 * @param httpSession
	 * @param model
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/getDown")
	public String getDown() throws Exception{
		 return "system/common/down";
	}
	
	@RequestMapping("/goChangePwd")
	public String goChangePwd(@RequestParam(required=true) String operatorUserId,ModelMap model) throws Exception{
		model.addAttribute("txtUserId",operatorUserId);
		return "system/common/changePwd";
	}
	
	
	//*******************角色模块**********************
	
	
	/**
	 * 跳转到角色列表页面
	 * @throws Exception 
	 */
	@RequestMapping("/goRoleList")
	public String goRoleList(ModelMap model) throws Exception {
		List<SysParameter> roleStateList = sysParameterService.getParamListByCode("roleState");
		model.addAttribute("roleStateList",roleStateList);
		model.addAttribute("roleStateListJSON",JsonTool.toJsonString(roleStateList));
		return "system/role/roleList";
	}

	/**
	 * 跳转到角色详情页面
	 * @throws Exception 
	 */
	@RequestMapping("/goRoleDetail")
	public String goRoleDetail(ModelMap model,@RequestParam Integer roleId) throws Exception {
		SysRole role = sysRoleService.getRoleById(roleId);
		model.addAttribute("role",role);
		return "system/role/roleDetail";
	}
	
	/**
	 * 跳转到角色修改页面
	 * @throws Exception 
	 */
	@RequestMapping("/goRoleUpdate")
	public String goRoleUpdate(ModelMap model,@RequestParam Integer roleId) throws Exception {
		SysRole role = sysRoleService.getRoleById(roleId);
		if (role != null) {
			model.addAttribute("role",role);
			String menuIds = sysRoleService.queryMenuIdStrsByRoleId(roleId);
			model.addAttribute("oldMenuIds", menuIds);
		}
		return "system/role/roleUpdate";
	}
	
	//*******************菜单模块**********************
	/**
	 * 跳转到菜单新增页面
	 * @throws Exception 
	 */
	@RequestMapping("/goMenuAdd")
	public String goMenuAdd(ModelMap model,@RequestParam Integer parentMenuId) throws Exception {
		SysMenu parentMenu = sysMenuService.sysMenuInfoById(parentMenuId);
		model.addAttribute("parentMenu",parentMenu);
		/**
		 * 老系统的权限设计字段，不太清楚等级
		 */
		if (parentMenu.getLevel() < 3) {
			List<SysParameter> lv23MenuIconList = sysParameterService.getParamListByCode("lv23MenuIcon");
			model.addAttribute("menuIconList",lv23MenuIconList);
		}else if (parentMenu.getLevel() == 3) {
			List<SysParameter> lv4MenuIconList = sysParameterService.getParamListByCode("lv4MenuIcon");
			model.addAttribute("menuIconList",lv4MenuIconList);
		}
		return "system/menu/menuAdd";
	}
	
	//*******************分组模块**********************
	/**
	 * 跳转到分组页面
	 * @throws Exception 
	 */
	@RequestMapping("/goGroupList")
	public String goGroupList(ModelMap model,HttpSession httpSession) throws Exception {
		List<SysParameter> groupTypeList = sysParameterService.getParamListByCode("groupType");
		model.addAttribute("groupTypeList",groupTypeList);
		model.addAttribute("groupTypeListJSON",JsonTool.toJsonString(groupTypeList));
		logger.debug("groupTypeListJSON:"+JsonTool.toJsonString(groupTypeList));
		 SysUser loginUser = this.getLoginedUserInfo(httpSession);
		 if(!this.isSupperAdmin(loginUser)){ //非超级管理员	
			 model.addAttribute("loginedUserGroupId",loginUser.getGroupid());
		 }else{
			 model.addAttribute("loginedUserGroupId", "1");
		 }
		return "system/group/groupList";
	}
	
	/**
	 * 跳转到分组详情页面
	 * @throws Exception 
	 */
	@RequestMapping("/goGroupDetail")
	public String goGroupDetail(ModelMap model,HttpSession httpSession,@RequestParam Integer groupId)  throws Exception {
		List<SysParameter> userStateList = sysParameterService.getParamListByCode("userState");
		model.addAttribute("userStateList",userStateList);
		model.addAttribute("userStateListJSON",JsonTool.toJsonString(userStateList));
		List<SysParameter> empStateList = sysParameterService.getParamListByCode("empState");
		model.addAttribute("empStateList",empStateList);
		model.addAttribute("empStateListJSON",JsonTool.toJsonString(empStateList));
		SysGroup group = sysGroupService.getGroupById(groupId);
		model.addAttribute("group",group);
		return "system/group/groupDetail";
	}
	
	/**
	 * 添加分组页面
	 * @param model
	 * @param parentGroupId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goGroupAdd")
	public String goGroupAdd(ModelMap model,@RequestParam Integer parentGroupId)  throws Exception {
		SysGroup parentGroup = sysGroupService.getGroupById(parentGroupId);
		model.addAttribute("parentGroup",parentGroup);
		return "system/group/groupAdd";
	}
	
	/**
	 * 修改分组页面
	 * @param model
	 * @param groupId
	 * @return
	 * @throws Exception
	 */
	@RequestMapping("/goGroupUpdate")
	public String goGroupUpdate(ModelMap model,@RequestParam Integer groupId) throws Exception {
		SysGroup group = sysGroupService.getGroupById(groupId);
		model.addAttribute("group", group);
		return "system/group/groupUpdate";
	}
	
	
	//*******************用户模块**********************
		/**
		 * 跳转到用户列表页面
		 * @throws Exception 
		 */
		@RequestMapping("/goUserList")
		public String goUserList(ModelMap model,HttpSession httpSession) throws Exception {
			List<SysParameter> userStateList = sysParameterService.getParamListByCode("userState");
			model.addAttribute("userStateList", userStateList);
			model.addAttribute("userStateListJSON", JsonTool.toJsonString(userStateList));
		
		    SysUser loginUser = this.getLoginedUserInfo(httpSession);
		    Integer groupId = 1;
			if(!this.isSupperAdmin(loginUser)){
			    groupId = loginUser.getGroupid();
			}
			List<SysGroup> groupList = sysUserService.getGroupWithSubListByGroupId(groupId.toString());
			model.addAttribute("qGroupList", groupList);
			return "system/user/userList";
		}
		
		/**
		 * 跳转到用户详情
		 * @param model
		 * @param httpSession
		 * @param userId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goUserDetail")
		public String goUserDetail(ModelMap model,HttpSession httpSession,@RequestParam Integer userId)  throws Exception {
			SysUser user = sysUserService.sysUserInfoById(userId);
			model.addAttribute("user",user);
			SysParameter roleName = sysParameterService.getParamByCodeAndValue("userState", user.getUserstate());
			model.addAttribute("user_userstate", null != roleName? roleName.getName():"");
			model.addAttribute("user_createtime",user.getCreatetime() == null ? "" : DateTimeUtil.getTimeFmt(user.getCreatetime(),DateTimeUtil.FORMAT3));
            return "system/user/userDetail";
		}
		
		
		/**
		 * 跳转到分组添加用户
		 * @param model
		 * @param httpSession
		 * @param userId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goUserAddWidthGroup")
		public String goUserAddWidthGroup(ModelMap model,HttpSession httpSession,@RequestParam Integer groupId)  throws Exception {
			SysGroup group = sysGroupService.getGroupById(groupId);
			SysGroup rootGroup = sysGroupService.getCompanyByGroup(group);
			model.addAttribute("group",group);
			model.addAttribute("company",rootGroup);
            return "system/user/userAddWithGroup";
		}

		/**
		 * 跳转到用户修改页面
		 * @param model
		 * @param httpSession
		 * @param userId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goUserUpdate")
		public String goUserUpdate(ModelMap model,HttpSession httpSession,@RequestParam Integer userId)  throws Exception {
			SysUser preUser = sysUserService.sysUserInfoById(userId);
			model.addAttribute("oldUser",preUser);
			return "system/user/userUpdate";
		}
		
		/**
		 * 跳转到用户分组设置页面
		 * @param model
		 * @param httpSession
		 * @param userId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goUserGroupSet")
		public String goUserGroupSet(ModelMap model,HttpSession httpSession,@RequestParam String userIds)  throws Exception {
			String[] userIdArray = userIds.split(",");
			List<Integer> userIdList = new ArrayList<Integer>();
			for (String s : userIdArray) {
				userIdList.add(Integer.valueOf(s));
			}
			List<SysUser> userList = sysUserService.listSysUserByIds(userIdList);
			if (userList == null ) {
				userList = new ArrayList<SysUser>(0);
			}
			BasePage<SysUser> page = new BasePage<SysUser>(userList.size(),userList);
			model.addAttribute("userIds",userIds);
			model.addAttribute("userGroupSetUserList",JsonTool.toJsonString(page));
			List<SysParameter> groupTypeList = sysParameterService.getParamListByCode("groupType");
			model.addAttribute("groupTypeList",groupTypeList);
			model.addAttribute("groupTypeListJSON",JsonTool.toJsonString(groupTypeList));
			return "system/user/userGroupSet";
		}
		
		/**
		 * 跳转到用户角色设置页面
		 * @param model
		 * @param httpSession
		 * @param userId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goUserRoleSet")
		public String goUserRoleSet(ModelMap model,HttpSession httpSession,@RequestParam String userIds)  throws Exception {
			String[] userIdArray = userIds.split(",");
			List<Integer> userIdList = new ArrayList<Integer>();
			for (String s : userIdArray) {
				userIdList.add(Integer.valueOf(s));
			}
			List<SysUser> userList = sysUserService.listSysUserByIds(userIdList);
			if (userList == null ) {
				userList = new ArrayList<SysUser>(0);
			}
			BasePage<SysUser> page = new BasePage<SysUser>(userList.size(),userList);
			model.addAttribute("userIds",userIds);
			model.addAttribute("userRoleSetUserList",JsonTool.toJsonString(page));
			return "system/user/userRoleSet";
		}
		
		
		//*******************参数模块**********************
		/**
		 * 参数列表
		 * @param model
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goParameterList")
		public String goParameterList(ModelMap model)  throws Exception {
			List<SysParameter> parameterTypeList = sysParameterService.getParamListByCode("parameterType");
			model.addAttribute("parameterTypeList", parameterTypeList);
			model.addAttribute("parameterTypeListJSON", JsonTool.toJsonString(parameterTypeList));
			return "system/parameter/parameterList";
		}
		
		/**
		 * 参数信息
		 * @param model
		 * @param parameterId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goParameterDetail")
		public String goParameterDetail(ModelMap model,@RequestParam Integer parameterId ) throws Exception {
			SysParameter parameter = sysParameterService.getParameterById(parameterId);
			model.addAttribute("parameter",parameter);
			return "system/parameter/parameterDetail";
		}
		
		/**
		 * 子参数列表
		 * @param model
		 * @param parameterId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goSubParameterList")
		public String goSubParameterList(ModelMap model,@RequestParam Integer parameterId) throws Exception {
			SysParameter parameter = sysParameterService.getParameterById(parameterId);
			model.addAttribute("parameter",parameter);
			return "system/subParameter/subParameterList";
		}
		
		/**
		 * 新增子参数
		 * @param model
		 * @param parameterId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goSubParameterAdd")
		public String goSubParameterAdd(ModelMap model,@RequestParam Integer parameterId) throws Exception {
			SysParameter parameter = sysParameterService.getParameterById(parameterId);
			model.addAttribute("parentParameter",parameter);
			List<SysParameter> parameterTypeList = sysParameterService.getParamListByCode("parameterType");
			List<SysParameter> parameterEffectTypeList = sysParameterService.getParamListByCode("parameterEffectType");
			model.addAttribute("parameterTypeList",parameterTypeList);
			model.addAttribute("parameterEffectTypeList",parameterEffectTypeList);
			return "system/subParameter/subParameterAdd";
		}
		
		/**
		 * 子参数编辑
		 * @param model
		 * @param parameterId
		 * @return
		 * @throws Exception
		 */
		@RequestMapping("/goSubParameterUpdate")
		public String goSubParameterUpdate(ModelMap model,@RequestParam Integer parameterId) throws Exception {
			SysParameter parameter = sysParameterService.getParameterById(parameterId);
			model.addAttribute("parameter",parameter);
			SysParameter parentParameter = sysParameterService.getParameterById(parameter.getParentId());
			if(parentParameter != null){
				model.addAttribute("parentParameter",parameter);
			}
			List<SysParameter> parameterTypeList = sysParameterService.getParamListByCode("parameterType");
			List<SysParameter> parameterEffectTypeList = sysParameterService.getParamListByCode("parameterEffectType");
			model.addAttribute("parameterTypeList",parameterTypeList);
			model.addAttribute("parameterEffectTypeList",parameterEffectTypeList);
			return "system/subParameter/subParameterUpdate";
		}
		
		@RequestMapping("/goParameterUpdate")
		public String goParameterUpdate(ModelMap model,@RequestParam Integer parameterId) throws Exception {
			SysParameter parameter = sysParameterService.getParameterById(parameterId);
			model.addAttribute("parameter",parameter);
			List<SysParameter> parameterTypeList = sysParameterService.getParamListByCode("parameterType");
			List<SysParameter> parameterEffectTypeList = sysParameterService.getParamListByCode("parameterEffectType");
			model.addAttribute("parameterTypeList",parameterTypeList);
			model.addAttribute("parameterEffectTypeList",parameterEffectTypeList);
		    return "system/parameter/parameterUpdate";
		}
		
		/**
		 * 跳转到参数增加页面
		 */
		@RequestMapping("/goParameterAdd")
		public String goParameterAdd(ModelMap model) throws Exception {
				List<SysParameter> parameterTypeList = sysParameterService.getParamListByCode("parameterType");
				model.addAttribute("parameterTypeList", parameterTypeList);
				List<SysParameter> parameterEffectTypeList = sysParameterService.getParamListByCode("parameterEffectType");
				model.addAttribute("parameterEffectTypeList", parameterEffectTypeList);
			return "system/parameter/parameterAdd";
		}
		
	  /** 跳转到菜单管理页面 */
		@RequestMapping("/goMenuList")
	  public String goMenuList() {
	    return "system/menu/menuList";
	  }
}
